/**
 * - 在 cdnjs.com 或者 unpkg.com 上找到最新版本的 `mermaid.min.js`，
 *      保存到 `path_to/mermaid.min.js`
 * - 修改下面代码中的 `mermaidScript`，使用 `file://` 协议指向 `path_to/mermaid.min.js` 的 URL
 * - 修改后的代码保存到 `path_to/injection.js`，
 * - 在 Typora 的安装目录找到 path_to_typora\resources\app\window.html，
 *      `</body>` 前添加 `<script src="path_to/injection.js" async></script>`
 * - 注：如果 window.html 修改后不能保存，可以先拷贝出来修改后再拷贝回去覆盖
 */
import dark from "./dark.js";
import getVersion, { Version } from "./ext/version.js";

(async () => {
    const typora = {
        version: await getVersion(),
    }
    console.log("[About Typora]", typora);

    const mermaidScript = ((scriptName) => {
        return () => {
            // 虽然 Typora 使用了 jQuery，但不能保证 jQuery 脚本以此之前加载
            const [injection] = [...document.querySelectorAll("script")]
                .filter(el => /typora\/injection\.js$/i.test(el.src));
            if (!injection) { return; }
            const [, prefix] = injection.src.match(/^(.*)typora\/injection\.js$/);
            if (!prefix) { return; }
            return `${prefix}${scriptName}`;
        };
    })("mermaid.min.js");
    console.log(`load mermaid script from ${mermaidScript()}`);

    // deprecated 想别的办法注入样式
    const themeCSS = (() => {
        const themeStyles = dark;

        function changeCase(name) {
            return name.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);
        }

        const makeStyle = (styles, parents = []) => {
            const entries = Object.entries(styles);
            const [p, o] = entries.reduce(([p, o], it) => {
                if (typeof it[1] === "object") {
                    o.push(it);
                } else {
                    p.push(it);
                }
                return [p, o];
            }, [[], []]);

            const subs = o.flatMap(([k, v]) => makeStyle(v, [...parents, k]));
            if (p.length) {
                const lines = p.map(([k, v]) => `${changeCase(k)}: ${v};`);
                subs.unshift(`${parents.join(" ")} { ${lines.join(" ")} }`);
            }

            return subs;
        }

        return makeStyle(themeStyles).join(" ");
    })();

    const fixMermaidZoom = () => {
        if (!typora.version.lessThen(Version.fromString("0.11.7"))) {
            return;
        }

        // --mermaid-font-zoom 大于 1 会导致 Mermaid 图形中的文字越界（显示不全）
        // mermaid v0.11.7 已经修复了这个问题
        document.querySelector("html")
            .style.setProperty("--mermaid-font-zoom", 1);
        console.log("[fixed by injection] reset --mermaid-font-zoom to 1");
    };

    const mermaidConfig = {
        theme: "forest",
        // themeCSS,
        fontFamily: "Noto Sans CJK SC Light",
        fontZoom: 1,
        flowchart: {
            stroke: "#999",
            color: "#f0f0f0",
        }
    };

    const timer = setInterval(() => {
        if (window.editor?.diagrams && window.mermaidAPI) {
            fixMermaidZoom();
            const scriptUrl = mermaidScript();
            $.getScript(scriptUrl)
                .then(() => {
                    mermaidAPI = mermaid.mermaidAPI;
                    mermaid.initialize(mermaidConfig);
                    editor.diagrams.refreshDiagram(editor);
                    clearInterval(timer);
                });
        }
    }, 200);

    setTimeout(() => clearInterval(timer), 5000);
})();
